package service

import (
	"git.oschina.net/fanbuchi/xgggh/pay/database"
	pay "git.oschina.net/fanbuchi/xgggh/pay/proto/pay"
	order "git.oschina.net/fanbuchi/xgggh/order/proto/order"
	orderCli "git.oschina.net/fanbuchi/xgggh/order/cli"
	"errors"
	"git.oschina.net/fanbuchi/xgggh/utils/page"
)

type Pay struct {
	MmAppPay MmAppPay;
}

func (super *Pay)Create(req *pay.CreateReq) (*pay.WxAPPPayParams,error)  {
	if req.Order == nil||req.Order.Id<=0 {
		return nil,errors.New("order is not allowed null")
	}
	//查询订单
	orderQueryReq:=order.QueryReq{Id:req.Order.Id}
	orderRsp,err:=orderCli.Query(&orderQueryReq)
	if err !=nil {
		return nil,err
	}
	if orderRsp.Code!=0 {
		return nil,errors.New(orderRsp.Detail)
	}
	if orderRsp.Order ==nil  {
		return  nil,errors.New("can`t find order")
	}
	order:=orderRsp.Order
	//构建支付单
	payReq:=pay.Pay{OrderId:order.Id,
		Name:"充值",
		Fee:order.Fee,
		Numbers:1,
		PayWay:req.PayWay,
	}
	_,err=database.Master().InsertOne(&payReq)
	if err !=nil {
		return nil,err
	}
	//微信app支付下单
	if payReq.PayWay ==pay.PayWay_wxPay {
		// 微信app支付统一下单
		unifiedOrderRsp,err:=super.MmAppPay.UnifiedOrder(&payReq)
		if err !=nil{
			return nil,err
		}
		//拼接唤醒app参数
		payParams,err:=super.MmAppPay.AwakenPayApp(unifiedOrderRsp)
		return payParams,err
	}else{
		return nil,errors.New("can`t support pay way")
	}
	return nil,err
}

//通知
func (super *Pay)Notify(req *pay.NotifyReq) (error)  {
	//Sign
	if req.PayWay==pay.PayWay_wxPay {
		//解参数-解签名
		result,err:=super.MmAppPay.NotifySign(req.Params)
		if err !=nil{
			payParams:=pay.Pay{Id:result.PayId,
				OrderId:result.OrderId,
				PayResult:err.Error(),
			}
			_,err=super.Update(&payParams)
			return nil
		}
		//数据库记录，更新支付状态
		params:=order.UpdateReq{Id:result.OrderId,OrderStatus:order.OrderStatus_payed}
		_,err=orderCli.Update(&params)
		if err!=nil {
			return err
		}
	}
	return nil
}


func (super *Pay)Delete(req *pay.DeleteReq) error  {
	if req.Id <= 0 {
		err := errors.New("column Id required")
		return err
	}
	tmp:=pay.Pay{Id:req.Id}
	clomns,err:= database.Master().Delete(&tmp)
	if clomns == 0 {
		err := errors.New("0 rows was deleted")
		return err
	}
	return err
}

func (super *Pay)Update(pay *pay.Pay)(*pay.Pay,error){
	nums,err:=database.Master().Update(pay)
	if err !=nil{
		return nil,err
	}
	if nums<=0 {
		return nil,errors.New("o rows was update")
	}
	return pay,nil
}

func (super *Pay)Query(req *pay.QueryReq) ( *pay.Pay, error)  {
	if req.Id <= 0 {
		err := errors.New("column Id required")
		return nil,err
	}

	var tmp pay.Pay
	_,err:= database.Master().ID(req.Id).Unscoped().Get(&tmp)
	return &tmp,err
}

func (super *Pay)Search(req *pay.SearchReq) ([]*pay.Pay,error)  {
	limit,offset:=page.Page(req.PageNumber,req.ResultPerPage)
	params:=req.Params
	if params==nil {
		params=&pay.Pay{}
	}
	var tmp []*pay.Pay;
	err:= database.Master().Limit(limit,offset).Find(&tmp,params)
	return tmp,err
}
